package 高效制胜._02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/9/8 9:32
 * 三数之和
 * 算法：排序  双指针
 * 将数组排序，这样就可以用二分查找的方式来查找
 */
public class _15 {
    public static void main(String[] args) {
        System.out.println(new _15().threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) break;
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                if (l != i + 1 && nums[l] == nums[l - 1]) {
                    ++l;
                    continue;
                }
                if (r != nums.length - 1 && nums[r] == nums[r + 1]) {
                    --r;
                    continue;
                }
                int tem = nums[l] + nums[r] + nums[i];
                if (tem == 0) {
                    ans.add(Arrays.asList(nums[i], nums[l], nums[r]));
                    ++l;
                    --r;
                }
                else if (tem > 0)  r--;
                else l++;
            }
        }
        return ans;
    }

}
